package ase.assignment.sts.servlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ase.assignment.sts.api.CustomHandler;
import ase.assignment.sts.utils.STSConstants;

/**
 * Servlet implementation class for Servlet: LoginServlet
 * 
 * @web.servlet name="LoginServlet" display-name="LoginServlet"
 * 
 * @web.servlet-mapping url-pattern="/LoginServlet"
 * 
 */
public class LoginServlet extends javax.servlet.http.HttpServlet implements
		javax.servlet.Servlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 6147142753674123630L;

	/*
	 * (non-Java-doc)
	 * 
	 * @see javax.servlet.http.HttpServlet#HttpServlet()
	 */
	public LoginServlet() {
		super();
	}

	/*
	 * (non-Java-doc)
	 * 
	 * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request,
	 *      HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/*
	 * (non-Java-doc)
	 * 
	 * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request,
	 *      HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		boolean isLogin = CustomHandler.getInstance().login(username, password);
		if (isLogin) {
			request.getSession().setAttribute(STSConstants.SESSION_USER,
					username);
			response.sendRedirect("main.jsp");
		} else {
			response.sendRedirect("login.jsp?error=Login fail&username="
					+ username);
		}
	}
}